
package com.craterhill.java.ems.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AutoPopulatingList;

import com.craterhill.java.ems.common.beans.GradingRules;
import com.craterhill.java.ems.common.beans.MarkingPeriods;
import com.craterhill.java.ems.common.beans.Session;
import com.craterhill.java.ems.dao.GradingRulesDao;
import com.craterhill.java.ems.dao.MarkingPeriodDao;
import com.craterhill.java.ems.dao.SessionDao;
import com.craterhill.java.ems.service.SessionService;

@Service
public class SessionServiceImpl implements SessionService {

	private final SessionDao sessionDao;
	private final MarkingPeriodDao markingPeriodDao;
	private final GradingRulesDao gradingRulesDao;

	@Autowired
	public SessionServiceImpl(final SessionDao sessionDao, final MarkingPeriodDao markingPeriodDao, final GradingRulesDao gradingRulesDao) {
		this.sessionDao = sessionDao;
		this.markingPeriodDao = markingPeriodDao;
		this.gradingRulesDao = gradingRulesDao;
	}

	@Override
	public Session saveSession(final Session session) {
		int newSessionId = sessionDao.save(session);
		markingPeriodDao.save(newSessionId, session.getMarkingPeriods());
		gradingRulesDao.save(newSessionId, session.getGradingRules());
		session.setSessionId(newSessionId);
		return session;
	}

	@Override
	public boolean updateSession(final Session session) {

		int sessionId = session.getSessionId();
		sessionDao.update(session);

		markingPeriodDao.remove(sessionId);
		gradingRulesDao.remove(sessionId);

		markingPeriodDao.save(sessionId, session.getMarkingPeriods());
		gradingRulesDao.save(sessionId, session.getGradingRules());

		return true;
	}

	@Override
	public List<Session> getSessions(int schoolId) {
		return sessionDao.findBySchool(schoolId);
	}

	@Override
	public Session getSession(final int sessionId) {
		Session session = sessionDao.find(sessionId);
		session.setMarkingPeriods(new AutoPopulatingList<MarkingPeriods>(markingPeriodDao.findBySession(sessionId), MarkingPeriods.class));
		session.setGradingRules(new AutoPopulatingList<GradingRules>(gradingRulesDao.findBySession(sessionId), GradingRules.class));
		return session;
	}

	public boolean removeSession(final int sessionId) {
		return sessionDao.remove(sessionId);
	}
}
